<template>
  <view style="padding: 10px;">
    <image-picker label="违纪学生照片" :value="violationPatrolDetail.images" :readonly="true">
      <view style="flex-direction: row;margin-left: 35rpx">
        <button type="primary" style="flex: 1" @click="showAddDialog" v-if="false">选择违纪学生</button>
        <view style="font-size: 20px; margin-bottom: 10px;">{{violationPatrolDetail.studentName?'学生姓名：'+violationPatrolDetail.studentName:''}}</view>
        <view style="font-size: 20px; ">{{violationPatrolDetail.className?'班级：'+violationPatrolDetail.className:''}}</view>
      </view>
    </image-picker>
    <uni-section title="违纪类型" type="line">
      <dict-select :options.sync="violationTypeOptions" type="text" ref="violationTypeNode" dict-type="violation_type" v-model="violationPatrolDetail.violationType"/>
    </uni-section>
    <uni-section title="违纪学生人数" type="line">
      <text style="margin-left: 20rpx">{{violationPatrolDetail.studentNum}}</text>
    </uni-section>
    <uni-section title="违纪情况说明" type="line">
      <text style="margin-left: 20rpx">{{violationPatrolDetail.note}}</text>
    </uni-section>
    <uni-section title="违纪时间" type="line" style="margin-top: 20rpx">
      <text style="margin-left: 20rpx">{{violationPatrolDetail.violationTime}}</text>
    </uni-section>
    <uni-section title="违纪已认领" type="line" style="margin-top: 20rpx;">
      <uni-list>
        <uni-list-item
          thumb-size="lg"
          :title="item.studentName"
          :thumb="handleImageUrl(item.stuPhoto)"
          :note="item.className"
          v-for="(item,index) in violationReceiveInfos"
          :key="index">
          <template v-slot:footer>
            <view style="display: flex;flex-direction: column;align-items: end">
              <text style="color:#999;font-size: 11px">{{item.receiveTime}}</text>
              <view style="align-self: flex-end">
                <uni-badge type="warning" :text="getViolationText(item)"/>
                <uni-icons style="margin-left: 10rpx;align-self: center" type="trash" @click="goBackViolation(item)" v-if="showGoBackBtn(item)"/>
              </view>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </uni-section>
    <uni-section v-if="violationPatrolDetail && violationPatrolDetail.status!==4" title="违纪待认领" type="line" style="margin-top: 20rpx;">
      <uni-list>
        <uni-list-item
            v-for="(item,index) in needAddViolationStudentInfos"
            :key="index">
          <template v-slot:body>
            <view style="display: flex;gap: 10rpx">
              <view class="list-item-text">
                <text class="list-item-text-title">{{item.studentName}}</text>
                <text class="list-item-text-note">{{item.className}}</text>
              </view>
              <view style="display: flex;flex-direction: column;justify-content: center">
                <text style="font-size: 12px;align-self: center;margin-bottom: 10rpx">选择违纪图片</text>
                <uni-number-box style="margin-left: 10rpx;height: 50rpx" :min="1" :max="violationImagesSize" v-model="item.violationImageIndexSelect" />
              </view>
              <uni-easyinput style="margin-left: 10rpx" trim v-model="item.violationContent" :clearable="false" placeholder="请输入违纪内容"/>
              <uni-icons style="margin-left: 10rpx;align-self: center" type="trash" @click="deleteNeedAddViolationStudent(index)"/>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
      <view style="display: flex;gap: 10rpx">
        <button type="primary" style="flex: 1" @click="showAddDialog" v-if="canAddStudent">选择违纪学生</button>
        <button type="primary" style="flex: 1" @click="receiveViolation" v-if="notEmpty(needAddViolationStudentInfos) && !receiveDisabled">认领</button>
      </view>
    </uni-section>


    <uni-popup ref="popup" background-color="#fff">
      <view class="popup-content">
        <uni-data-select
            v-model="classId"
            :localdata="classOptions"
            placeholder="请选择班级"
            @change="changeClass">
        </uni-data-select>
        <scroll-view :scroll-y="true" style="max-height: 500rpx;margin-top: 10rpx;margin-bottom: 20rpx" @scrolltolower="loadMore">
          <uni-list>
            <uni-list-item
                v-for="item in queryStudentInfos"
                show-switch
                :thumb="item.stuPhoto"
                :title="item.studentName"
                :note="item.className"
                @switchChange="studentSwitchChange(item,$event)">
            </uni-list-item>
          </uni-list>
        </scroll-view>
        <button type="primary" @click="addNewViolationStudents">添加</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import student from '@/api/modules/student'
import teacherClass from '@/api/modules/teachClass'
import violationPatrolApi from "@/api/modules/violationPatrol";
import UniList from "../../../uni_modules/uni-list/components/uni-list/uni-list.vue";
import UniListItem from "../../../uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import UniForms from "../../../uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "../../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "../../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniDataSelect from "../../../uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import UniIcons from "../../../uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import DictSelect from "../../../components/dict-select/index.vue";

export default {
  components: {DictSelect, UniIcons, UniDataSelect, UniEasyinput, UniFormsItem, UniForms, UniListItem, UniList},
  data() {
    return {
      id: null,
      loginName: null,
      receiveDisabled: false,
      violationPatrolDetail: {},
      violationReceiveInfos: [],
      needAddViolationStudentInfos: [],
      queryStudentInfoPage : 1,
      queryStudentInfoTotalPage : null,
      queryStudentInfoPageSize: 10,
      queryStudentInfos: [],
      classOptions: [],
      classId: null,
      violationImagesSize: null,
      violationTypeOptions: [],
    }
  },
  onLoad(option) {
    this.id = option.id;
    this.loginName = uni.getStorageSync("loginName");
  },
  onShow() {
    this.getViolationPatrolDetail();
    this.getViolationReceiveInfos();
  },

  computed: {
    canAddStudent(){
      return this.violationPatrolDetail.studentNum-this.violationReceiveInfos.length-this.needAddViolationStudentInfos.length > 0
    }
  },

  methods: {
    showGoBackBtn(item){
      return item.receiveTeacherUserName===this.loginName;
    },
    getViolationText(classDv){
      // noinspection EqualityComparisonWithCoercionJS
      let option = this.violationTypeOptions.find(item=>item.dictValue==classDv.dvType);
      return !option ? "" : option.dictLabel||"";
    },
    deleteNeedAddViolationStudent(index){
      let violationStudentInfo = this.needAddViolationStudentInfos[index];
      violationStudentInfo.checked=false;
      this.needAddViolationStudentInfos.splice(index,1);
    },
    addNewViolationStudents(){
      let studentInfos = this.queryStudentInfos.filter(item=>item.checked);
      let allowAddNum = this.violationPatrolDetail.studentNum-this.violationReceiveInfos.length-this.needAddViolationStudentInfos.length;
      if(studentInfos.length > allowAddNum){
        this.toast("最多还能添加"+allowAddNum+"个违纪学生");
        return;
      }
      this.needAddViolationStudentInfos = [...this.needAddViolationStudentInfos,...studentInfos];
      let indexSelects = new Set(this.needAddViolationStudentInfos.map(item=>item.violationImageIndexSelect));
      let index = 1;
      this.needAddViolationStudentInfos.forEach(item=>{
        this.$set(item,'violationContent',this.violationPatrolDetail.note);
        if(!item.violationImageIndexSelect && !indexSelects.has(index)){
          item.violationImageIndexSelect = index;
        }
        index++;
      });
      this.trimAddStudentInfos(this.queryStudentInfos);
      this.resetStudentQueryContext(true);
      this.$refs.popup.close();
    },
    studentSwitchChange(student,event){
      student.checked = event.value;
    },
    changeClass(){
      this.resetStudentQueryContext();
      this.getStudentList();
    },
    getClassIdAndNames(){
      teacherClass.getClassIdAndNames().then(res=>{
        this.handleRes(res).then(data=>{
          if(data){
            data = data.map(item=>{
              return {value: item.id,text:item.name};
            })
          }
          this.classOptions = data;
        })
      });
    },
    resetStudentQueryContext(resetCLassId=false){
      this.queryStudentInfos = [];
      this.queryStudentInfoPage = 1;
      this.queryStudentInfoTotalPage = null;
      if(resetCLassId){
        this.classId = null;
      }
    },
    loadMore(){
      if(this.queryStudentInfoTotalPage && this.queryStudentInfoPage >= this.queryStudentInfoTotalPage){
        console.log("所有数据已加载完毕,无需在加载");
        return;
      }
      this.queryStudentInfoPage++;
      this.getStudentList();
    },
    getStudentList(){
      let paras = {page: this.queryStudentInfoPage,pageSize: this.queryStudentInfoPageSize,classId:this.classId};
      student.getFilterStudentPage(paras).then(res=>{
        this.handleRes(res).then(data=>{
          let list = this.trimAddStudentInfos(data.list);
          this.queryStudentInfos=[...this.queryStudentInfos,...list]
          this.queryStudentInfoTotalPage=data.totalPage;
        });
      })
    },
    trimAddStudentInfos(studentInfos){
      if(this.isEmpty(studentInfos)){
        return studentInfos;
      }
      if(this.notEmpty(this.needAddViolationStudentInfos)){
        let ids = this.needAddViolationStudentInfos.map(item=>item.id);
        let idSet = new Set(ids);
        studentInfos = studentInfos.filter(info=>!idSet.has(info.id));
      }
      if(this.notEmpty(this.violationReceiveInfos)){
        let ids = this.violationReceiveInfos.map(item=>item.studentId);
        let idSet = new Set(ids);
        studentInfos = studentInfos.filter(info=>!idSet.has(info.id));
      }
      return studentInfos;
    },
    getViolationReceiveInfos(){
      if(!this.id){
        return;
      }
      violationPatrolApi.getViolationPatrolReceiveInfos(this.id).then(res=>{
        this.handleRes(res,null,true).then(data=>{
          this.violationReceiveInfos = data;
        });
      }).catch(err=>{
        console.error("获取违纪认领信息失败",err);
        this.toast("获取违纪认领信息失败",1500,"error")
      });
    },
    getViolationPatrolDetail(){
      if(!this.id){
        return;
      }
      violationPatrolApi.getViolationPatrolDetailInfo(this.id).then(res=>{
        console.log("getViolationPatrolDetail",res);
        this.violationPatrolDetail = res.data;
        this.violationPatrolStatus = this.violationPatrolDetail.status;
        this.violationImagesSize = this.violationPatrolDetail.images.split(',').length;
      }).catch(err=>{
        console.error("获取违纪详情失败",err);
        this.toast("获取违纪详情失败",1500,"error")
        this.goBack(1000);
      });
    },
    showAddDialog(){
      if(this.isEmpty(this.classOptions)){
        this.getClassIdAndNames();
      }
      if(this.isEmpty(this.queryStudentInfos)){
        this.getStudentList();
      }
      this.$refs.popup.open("center");
    },

    receiveViolation(){
      if(this.receiveDisabled){
        this.toast("认领中");
        return;
      }
      this.receiveDisabled = true;
      if(this.isEmpty(this.needAddViolationStudentInfos)){
        this.toast("请添加待认领的违纪学生");
        this.receiveDisabled = false;
        return;
      }
      for (let item of this.needAddViolationStudentInfos){
        if(!item.violationImageIndexSelect || item.violationImageIndexSelect < 1){
          this.toast("请选择正确的违纪图片");
          this.receiveDisabled = false;
          return;
        }
        if(this.isEmpty(item.violationContent)){
          this.toast("违纪内容不能为空");
          this.receiveDisabled = false;
          return;
        }
      }
      this.needAddViolationStudentInfos.forEach(item=>item.violationImageIndex=item.violationImageIndexSelect - 1);
      let body = {
        violationPatrolId:this.violationPatrolDetail.id,
        violationStudentInfos: this.needAddViolationStudentInfos
      };
      violationPatrolApi.receiveStudents(body).then(res=>{
        this.handleRes(res,"认领成功",true).then(()=>{
          setTimeout(()=>{
            this.goBack();
          },1000)
        });
      }).catch(error=>{
        this.receiveDisabled = false;
        console.log("error",error)
        this.toast(this.getErrorResMsg(error,"认领失败"))
      })
    },
    goBackViolation(item){
      if(item.loading){
        this.toast("回退中");
        return;
      }
      item.loading = true;
      violationPatrolApi.goBackStudents({violationPatrolId:item.violationPatrolId,dvId: item.dvId}).then(res=>{
        this.handleRes(res,"回退成功",true).then(()=>{
          this.getViolationPatrolDetail();
          this.getViolationReceiveInfos();
        })
      }).catch(err=>{
        console.log('退回违纪学生出错',err);
        this.toast(this.getErrorResMsg(err));
        if(item.hasOwnProperty('loading')){
          delete item.loading;
        }
      })
    },
  }
}
</script>

<style>
.popup-content {
  width: 500rpx; /* 或固定宽度，如 300px */
  margin: 0 auto; /* 水平居中 */
  padding: 20px;
}
.list-item-text {
  display: flex;
  color: #3b4144;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
}
.list-item-text-title {
  font-size: 12px;
  color: #3b4144;
  overflow: hidden;
}
.list-item-text-note {
  margin-top: 6rpx;
  color: #999;
  font-size: 10px;
  overflow: hidden;
}
</style>
